package com.baosight.risk.common.filter;

import com.baosight.iplat4j.core.security.web.PlatformAuthenticationProcessingFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author phinxe
 * @Date 2019-07-04
 */
@Slf4j
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Autowired
    private PlatformAuthenticationPostHandler platformAuthenticationPostHandler;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        // 允许指定域访问跨域资源
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        // 允许浏览器在预检请求成功之后发送的实际请求方法名
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        // 允许浏览器发送的请求消息头
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 允许客户端携带跨域cookie，此时origin值不能为“*”，只能为指定单一域名
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        // 浏览器缓存预检请求结果时间,单位:秒
        httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
        } else if (httpServletRequest.getMethod().equals("POST") && httpServletRequest.getRequestURI().equals("/risk/xtzy/company/getCompany")) {
            platformAuthenticationPostHandler.loginNew(httpServletRequest,httpServletResponse,filterChain);
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    @Override
    public void destroy() {

    }
}
